package cn.concurrence.productconsume;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author summit
 * @since 2022/4/25 11:28
 */
public class ProdConsTest2 {
	private Integer num = 0;


	private Lock lock = new ReentrantLock();

	private Condition condition = lock.newCondition();


	private void increment() throws InterruptedException {

		lock.lock();
		try {
			if (num != 0) {
				condition.await();
			}
			num++;
			System.out.println(Thread.currentThread().getName() + ":" + num);

			// 唤醒所有
			condition.signal();
		} finally {
			lock.unlock();
		}
	}

	private void decrement() throws InterruptedException {
		lock.lock();
		try {
			if (num == 0) {
				condition.await();
			}
			num--;
			System.out.println(Thread.currentThread().getName() + ":" + num);

			// 唤醒所有
			condition.signal();
		} finally {
			lock.unlock();
		}

	}

	public static void main(String[] args) {
		ProdConsTest2 prodConsTest1 = new ProdConsTest2();

		new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				try {
					prodConsTest1.increment();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}).start();


		new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				try {
					prodConsTest1.decrement();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}).start();
	}
}
